package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.controller.v1.ArticleHomeController;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApAuthorMapper apAuthorMapper;
    @Autowired
    GeneratePageService generatePageService;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;
    @Override

    public ResponseResult saveAticle(ArticleDto articleDto) {

        // 1. 封装 article对象
        ApArticle apArticle = dtoToArticle(articleDto);
        // 2. 保存或修改文章
        Long articleId = saveOrUpdateArticle(apArticle);
        // 3. 保存 文章 内容 和 配置 信息(id)
        saveContentAndConfig(articleId, articleDto.getContent());
        //返回文章ID
        generatePageService.generateArticlePage(apArticle.getId());

        return ResponseResult.okResult(apArticle.getId());
    }

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //校验参数
        if (dto == null) {
             dto = new ArticleHomeDto();
        }
        //页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        //设置频道
        if (StringUtils.isNotBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //设置页条数
        dto.setSize(size);
        //设置时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }

        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) || !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        //返回结果
        ResponseResult result = ResponseResult.okResult(apArticleList);
        result.setHost(webSite);
        return result;
    }





    private void saveContentAndConfig(Long articleId, String content) {
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        // 是否允许转发
        apArticleConfig.setIsForward(true);
        // 是否允许评论
        apArticleConfig.setIsComment(true);
        // 是否下架
        apArticleConfig.setIsDown(false);
        // 是否删除
        apArticleConfig.setIsDelete(false);
        // 文章id
        apArticleConfig.setId(articleId);
        apArticleConfigMapper.insert(apArticleConfig);

        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        // 文章内容
        apArticleContent.setContent(content);
        // 文章id
        apArticleContent.setId(articleId);
        apArticleContentMapper.insert(apArticleContent);
    }

    private Long saveOrUpdateArticle(ApArticle apArticle) {
        if (apArticle.getId() == null) {
            // 普通文章设置属性
            apArticle.setComment(0);
            apArticle.setLikes(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            // 保存
            save(apArticle);
        } else {
            // 5. 如果文章ID不为null 修改文章
            ApArticle aticle = getById(apArticle.getId());

            if (aticle == null) {
                log.error("文章信息不存在:{}", apArticle.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 并删除之前配置 和 文章内容
            // 删除之前配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, apArticle.getId()));
            // 删除之前内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            // 修改文章
            updateById(apArticle);
        }

        return apArticle.getId();
    }

    private ApArticle dtoToArticle(ArticleDto articleDto) {
        //TODO
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        // 根据自媒体用户id 查询 作者id
        ApAuthor apAuthor = apAuthorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, articleDto.getWmUserId()));
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //设置Author属性：apArticle.set
        apArticle.setAuthorName(apAuthor.getName());
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        return apArticle;
    }
}
